using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using DocumentCreationSystem.Models;

namespace DocumentCreationSystem.Services;

/// <summary>
/// 小说创作服务实现
/// </summary>
public class NovelCreationService : INovelCreationService
{
    private readonly ILogger<NovelCreationService> _logger;
    private readonly IDataStorageService _dataStorage;
    private readonly IAIService _aiService;
    private readonly IVectorService _vectorService;
    private readonly IDocumentService _documentService;
    private readonly IProjectToolsService _projectToolsService;
    private readonly TimelineService _timelineService;

    public NovelCreationService(
        ILogger<NovelCreationService> logger,
        IDataStorageService dataStorage,
        IAIService aiService,
        IVectorService vectorService,
        IDocumentService documentService,
        IProjectToolsService projectToolsService,
        TimelineService timelineService)
    {
        _logger = logger;
        _dataStorage = dataStorage;
        _aiService = aiService;
        _vectorService = vectorService;
        _documentService = documentService;
        _projectToolsService = projectToolsService;
        _timelineService = timelineService;
    }

    public async Task<NovelProject> CreateNovelProjectAsync(int projectId, string title, string description, int targetChapters, int targetWordsPerChapter)
    {
        var novelProject = new NovelProject
        {
            ProjectId = projectId,
            Title = title,
            CreativeDirection = description,
            TargetChapterCount = targetChapters,
            TargetWordsPerChapter = targetWordsPerChapter,
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow
        };

        await _dataStorage.CreateNovelProjectAsync(novelProject);

        _logger.LogInformation($"创建小说项目: {title} (ID: {novelProject.Id})");
        return novelProject;
    }

    public async Task<string> GenerateOverallOutlineAsync(int novelProjectId, string creativeDirection, int volumeCount = 10)
    {
        try
        {
            var novelProject = await _dataStorage.GetNovelProjectAsync(novelProjectId);

            if (novelProject == null)
            {
                _logger.LogError($"小说项目不存在: {novelProjectId}");
                throw new ArgumentException($"小说项目不存在: {novelProjectId}。请确保项目已正确创建。");
            }

            var prompt = $@"
请为以下小说项目生成一个详细的全书大纲：

小说标题：{novelProject.Title}
创作方向：{creativeDirection}
目标章节数：{novelProject.TargetChapterCount}
每章字数：{novelProject.TargetWordsPerChapter}
分卷数量：{volumeCount}卷

请生成一个包含以下内容的全书大纲：
1. 故事背景和世界观设定
2. 主要角色介绍和关系
3. 核心冲突和主线情节
4. 分卷结构建议（请严格按照{volumeCount}卷进行规划）
5. 整体故事发展脉络
6. 预期的高潮和结局

请确保大纲具有足够的深度和细节，能够支撑{novelProject.TargetChapterCount}章的长篇创作，并且严格按照{volumeCount}卷进行规划。
";

            var outline = await _aiService.GenerateTextAsync(prompt, 4000, 0.8f);
            
            // 保存大纲到数据存储
            novelProject.OverallOutline = outline;
            novelProject.UpdatedAt = DateTime.Now;
            await _dataStorage.UpdateNovelProjectAsync(novelProject);

            _logger.LogInformation($"生成全书大纲完成，项目ID: {novelProjectId}");
            return outline;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"生成全书大纲失败，项目ID: {novelProjectId}");
            throw;
        }
    }

    public async Task<List<VolumeOutline>> GenerateVolumeOutlinesAsync(int novelProjectId, string overallOutline, int volumeCount = 10)
    {
        try
        {
            var novelProject = await _dataStorage.GetNovelProjectAsync(novelProjectId);

            if (novelProject == null)
            {
                _logger.LogError($"小说项目不存在: {novelProjectId}");
                throw new ArgumentException($"小说项目不存在: {novelProjectId}。请确保项目已正确创建。");
            }

            var volumeOutlines = new List<VolumeOutline>();
            var chaptersPerVolume = novelProject.TargetChapterCount / volumeCount;

            for (int i = 1; i <= volumeCount; i++)
            {
                var prompt = $@"
基于以下全书大纲，请为第{i}卷生成详细的卷宗大纲：

全书大纲：
{overallOutline}

第{i}卷信息：
- 卷数：{i}/{volumeCount}
- 预计章节数：{chaptersPerVolume}
- 起始章节：{(i - 1) * chaptersPerVolume + 1}
- 结束章节：{i * chaptersPerVolume}

请生成包含以下内容的卷宗大纲：
1. 本卷的核心主题和目标
2. 主要情节发展
3. 角色成长和变化
4. 重要事件和转折点
5. 与前后卷的衔接
6. 本卷的高潮和结尾

请确保大纲与全书大纲保持一致，并为后续的章节创作提供充分的指导。
";

                var volumeOutlineText = await _aiService.GenerateTextAsync(prompt, 2000, 0.8f);
                
                var volumeOutline = new VolumeOutline
                {
                    VolumeNumber = i,
                    Title = $"第{i}卷",
                    Description = volumeOutlineText,
                    StartChapter = (i - 1) * chaptersPerVolume + 1,
                    EndChapter = i * chaptersPerVolume,
                    MainPlot = $"第{i}卷主要情节",
                    KeyEvents = new List<string>(),
                    CharacterDevelopments = new List<string>()
                };

                volumeOutlines.Add(volumeOutline);
                
                // 添加延迟避免API限制
                await Task.Delay(1000);
            }

            // 保存卷宗大纲到数据存储
            novelProject.VolumeOutlines = JsonConvert.SerializeObject(volumeOutlines);
            novelProject.UpdatedAt = DateTime.Now;
            await _dataStorage.UpdateNovelProjectAsync(novelProject);

            _logger.LogInformation($"生成卷宗大纲完成，项目ID: {novelProjectId}, 卷数: {volumeCount}");
            return volumeOutlines;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"生成卷宗大纲失败，项目ID: {novelProjectId}");
            throw;
        }
    }

    public async Task<string> GenerateChapterOutlineAsync(int novelProjectId, VolumeOutline volumeOutline, int chapterNumber)
    {
        try
        {
            var novelProject = await _dataStorage.GetNovelProjectAsync(novelProjectId);

            if (novelProject == null)
            {
                _logger.LogError($"小说项目不存在: {novelProjectId}");
                throw new ArgumentException($"小说项目不存在: {novelProjectId}。请确保项目已正确创建。");
            }

            // 获取相关的卷宗大纲
            var volumeOutlines = string.IsNullOrEmpty(novelProject.VolumeOutlines) 
                ? new List<VolumeOutline>()
                : JsonConvert.DeserializeObject<List<VolumeOutline>>(novelProject.VolumeOutlines) ?? new List<VolumeOutline>();

            var relevantVolume = volumeOutlines.FirstOrDefault(v => 
                chapterNumber >= v.StartChapter && chapterNumber <= v.EndChapter);

            // 获取前几章的内容作为上下文
            var allChapters = await _dataStorage.GetChaptersAsync(novelProjectId);
            var previousChapters = allChapters
                .Where(c => c.ChapterNumber < chapterNumber)
                .OrderByDescending(c => c.ChapterNumber)
                .Take(3)
                .ToList();

            var contextInfo = "";
            if (previousChapters.Any())
            {
                contextInfo = "前几章概要：\n";
                foreach (var chapter in previousChapters.OrderBy(c => c.ChapterNumber))
                {
                    contextInfo += $"第{chapter.ChapterNumber}章：{chapter.Title}\n";
                    if (!string.IsNullOrEmpty(chapter.Summary))
                    {
                        contextInfo += $"概要：{chapter.Summary}\n";
                    }
                }
            }

            var prompt = $@"
请为以下小说项目的第{chapterNumber}章生成详细的章节细纲：

小说信息：
- 标题：{novelProject.Title}
- 创作方向：{novelProject.CreativeDirection}
- 目标字数：{novelProject.TargetWordsPerChapter}字

{(relevantVolume != null ? $@"
相关卷宗大纲：
{relevantVolume.Outline}
" : "")}

{contextInfo}

全书大纲：
{novelProject.OverallOutline}

请生成包含以下内容的第{chapterNumber}章细纲：
1. 章节标题
2. 核心情节和事件
3. 角色行动和对话要点
4. 情感发展和冲突
5. 章节目标和推进作用
6. 与前后章节的衔接
7. 预期字数分配建议

请确保章节细纲与整体大纲保持一致，并为实际创作提供详细的指导。
";

            var outlineText = await _aiService.GenerateTextAsync(prompt, 2000, 0.8f);

            // 使用世界观设定工具增强章节细纲
            try
            {
                var project = await _dataStorage.GetProjectAsync(novelProject.ProjectId);
                if (project != null && !string.IsNullOrEmpty(project.RootPath))
                {
                    var enhancerParameters = new Dictionary<string, object>
                    {
                        ["chapterOutline"] = outlineText,
                        ["projectPath"] = project.RootPath,
                        ["chapterNumber"] = chapterNumber,
                        ["enhancementLevel"] = "标准"
                    };

                    var enhancementResult = await _projectToolsService.ExecuteToolAsync("chapter-outline-enhancer", enhancerParameters);

                    if (enhancementResult.IsSuccess && enhancementResult.Data.ContainsKey("enhancedOutline"))
                    {
                        outlineText = enhancementResult.Data["enhancedOutline"]?.ToString() ?? outlineText;
                        _logger.LogInformation($"章节细纲已通过世界观设定增强，项目ID: {novelProjectId}, 章节: {chapterNumber}");
                    }
                    else
                    {
                        _logger.LogWarning($"章节细纲增强失败，使用原始细纲，项目ID: {novelProjectId}, 章节: {chapterNumber}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"章节细纲增强过程出错，使用原始细纲，项目ID: {novelProjectId}, 章节: {chapterNumber}");
            }

            _logger.LogInformation($"生成章节细纲完成，项目ID: {novelProjectId}, 章节: {chapterNumber}");
            return outlineText;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"生成章节细纲失败，项目ID: {novelProjectId}, 章节: {chapterNumber}");
            throw;
        }
    }

    public async Task<string> GenerateChapterContentAsync(int novelProjectId, string chapterOutline, int chapterNumber, int targetWordCount = 6500)
    {
        try
        {
            var novelProject = await _dataStorage.GetNovelProjectAsync(novelProjectId);

            if (novelProject == null)
            {
                _logger.LogError($"小说项目不存在: {novelProjectId}");
                throw new ArgumentException($"小说项目不存在: {novelProjectId}。请确保项目已正确创建。");
            }

            // 获取角色信息
            var characters = await _dataStorage.GetCharactersAsync(novelProjectId);

            var characterInfo = "";
            if (characters.Any())
            {
                characterInfo = "主要角色信息：\n";
                foreach (var character in characters)
                {
                    characterInfo += $"- {character.Name}：{character.Description}\n";
                    if (!string.IsNullOrEmpty(character.Attributes))
                    {
                        characterInfo += $"  属性：{character.Attributes}\n";
                    }
                }
            }

            // 获取相关的历史内容
            var relatedContent = await GetRelatedHistoryContentAsync(novelProjectId, chapterOutline);

            // 获取世界观设定信息
            var worldSettingInfo = "";
            try
            {
                var project = await _dataStorage.GetProjectAsync(novelProject.ProjectId);
                if (project != null && !string.IsNullOrEmpty(project.RootPath))
                {
                    var worldSettingParameters = new Dictionary<string, object>
                    {
                        ["projectPath"] = project.RootPath,
                        ["settingFiles"] = "all",
                        ["outputFormat"] = "summary"
                    };

                    var worldSettingResult = await _projectToolsService.ExecuteToolAsync("world-setting-reader", worldSettingParameters);

                    if (worldSettingResult.IsSuccess && worldSettingResult.Data.ContainsKey("contents"))
                    {
                        var contents = worldSettingResult.Data["contents"] as Dictionary<string, object>;
                        if (contents != null && contents.Any())
                        {
                            worldSettingInfo = "相关世界观设定：\n";
                            foreach (var setting in contents.Take(5)) // 只取前5个最相关的设定
                            {
                                worldSettingInfo += $"- {setting.Key}：{setting.Value}\n";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"获取世界观设定信息失败，项目ID: {novelProjectId}");
            }

            // 获取时间线信息
            var timelineInfo = "";
            try
            {
                if (chapterNumber > 1)
                {
                    var previousChapterSummary = await _timelineService.GetPreviousChapterSummaryAsync(novelProject.ProjectId, chapterNumber - 1);
                    if (previousChapterSummary != null)
                    {
                        timelineInfo = $@"前章时间线状态：
角色变化：{previousChapterSummary.CharacterChanges}
势力变化：{previousChapterSummary.FactionChanges}
主要事件：{previousChapterSummary.MainEvents}
世界变化：{previousChapterSummary.WorldChanges}
";
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"获取时间线信息失败，项目ID: {novelProjectId}");
            }

            var prompt = $@"
请根据以下信息创作第{chapterNumber}章的正文内容：

章节细纲：
{chapterOutline}

{characterInfo}

{(relatedContent.Any() ? $@"
相关历史内容：
{string.Join("\n", relatedContent)}
" : "")}

{(!string.IsNullOrEmpty(worldSettingInfo) ? $@"
{worldSettingInfo}
" : "")}

{(!string.IsNullOrEmpty(timelineInfo) ? $@"
{timelineInfo}
" : "")}

创作要求：
1. 目标字数：{targetWordCount}字
2. 严格按照章节细纲进行创作
3. 保持与之前章节的连贯性
4. 确保角色行为符合设定
5. 严格遵循世界观设定和规则
6. 保持时间线的一致性和逻辑性
7. 角色状态和势力状态要与前章保持连贯
8. 情节发展自然流畅
9. 对话生动真实
10. 描写细腻丰富
11. 只输出章节正文内容，不要添加任何解释或总结

请开始创作第{chapterNumber}章的正文内容：
";

            var content = await _aiService.GenerateTextAsync(prompt, 8000, 0.9f);

            _logger.LogInformation($"生成章节内容完成，项目ID: {novelProjectId}, 章节: {chapterNumber}");
            return content;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"生成章节内容失败，项目ID: {novelProjectId}, 章节: {chapterNumber}");
            throw;
        }
    }

    public async Task<ConsistencyCheckResult> CheckConsistencyAsync(int novelProjectId, int chapterNumber, string content)
    {
        try
        {
            // 获取角色信息和历史内容
            var characters = await _dataStorage.GetCharactersAsync(novelProjectId);

            var allChapters = await _dataStorage.GetChaptersAsync(novelProjectId);
            var previousChapters = allChapters
                .Where(c => c.ChapterNumber < chapterNumber)
                .OrderByDescending(c => c.ChapterNumber)
                .Take(5)
                .ToList();

            var characterInfo = string.Join("\n", characters.Select(c => $"{c.Name}: {c.Description}"));
            var historyInfo = string.Join("\n", previousChapters.Select(c => $"第{c.ChapterNumber}章: {c.Summary}"));

            var prompt = $@"
请检查以下章节内容的一致性：

角色设定：
{characterInfo}

历史章节概要：
{historyInfo}

当前章节内容：
{content}

请检查以下方面的一致性：
1. 角色行为是否符合设定
2. 情节发展是否逻辑合理
3. 世界观设定是否一致
4. 时间线是否合理
5. 角色关系是否连贯

请以JSON格式返回检查结果，包含：
- isConsistent: 是否一致（true/false）
- issues: 发现的问题列表
- suggestions: 改进建议列表
- confidenceScore: 置信度分数（0-1）
";

            var result = await _aiService.GenerateTextAsync(prompt, 2000, 0.3f);
            
            try
            {
                var checkResult = JsonConvert.DeserializeObject<ConsistencyCheckResult>(result);
                return checkResult ?? new ConsistencyCheckResult { IsConsistent = true, ConfidenceScore = 0.5f };
            }
            catch
            {
                // 如果JSON解析失败，返回默认结果
                return new ConsistencyCheckResult 
                { 
                    IsConsistent = true, 
                    ConfidenceScore = 0.5f,
                    Issues = new List<string> { "无法解析一致性检查结果" }
                };
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"一致性检查失败，项目ID: {novelProjectId}, 章节: {chapterNumber}");
            return new ConsistencyCheckResult 
            { 
                IsConsistent = false, 
                ConfidenceScore = 0.0f,
                Issues = new List<string> { $"检查过程出错: {ex.Message}" }
            };
        }
    }



    private async Task<List<string>> GetRelatedHistoryContentAsync(int novelProjectId, string outline)
    {
        try
        {
            // 使用向量搜索找到相关的历史内容
            var searchResults = await _vectorService.SearchAsync(outline, "documents", 5, 0.6f);
            
            var relatedContent = new List<string>();
            foreach (var result in searchResults)
            {
                var document = await _dataStorage.GetDocumentAsync(result.DocumentId);

                if (document != null)
                {
                    relatedContent.Add($"来源：{document.FileName}\n内容：{result.Content}");
                }
            }
            
            return relatedContent;
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "获取相关历史内容失败");
            return new List<string>();
        }
    }

    private string ExtractTitleFromOutline(string outline)
    {
        // 简单的标题提取逻辑
        var lines = outline.Split('\n', StringSplitOptions.RemoveEmptyEntries);
        foreach (var line in lines)
        {
            if (line.Contains("标题") || line.Contains("章节"))
            {
                var parts = line.Split('：', ':', '：');
                if (parts.Length > 1)
                {
                    return parts[1].Trim();
                }
            }
        }
        
        return "未命名章节";
    }

    private async Task UpdateCharacterWithChanges(Character character, List<AttributeChange> changes, int chapterNumber)
    {
        try
        {
            var attributes = string.IsNullOrEmpty(character.Attributes)
                ? new Dictionary<string, object>()
                : JsonConvert.DeserializeObject<Dictionary<string, object>>(character.Attributes) ?? new Dictionary<string, object>();

            foreach (var change in changes)
            {
                attributes[change.Attribute] = change.NewValue;
            }

            character.Attributes = JsonConvert.SerializeObject(attributes);
            character.UpdatedAt = DateTime.Now;
            character.LastUpdatedChapter = chapterNumber;

            await _dataStorage.UpdateCharacterAsync(character);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"更新角色属性失败: {character.Name}");
        }
    }

    public async Task<Chapter> CreateChapterAsync(int novelProjectId, int chapterNumber, string title, string? outline = null)
    {
        try
        {
            var chapter = new Chapter
            {
                NovelProjectId = novelProjectId,
                ChapterNumber = chapterNumber,
                Title = title,
                Summary = outline ?? "",
                Content = "",
                WordCount = 0,
                Status = "Draft",
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };

            await _dataStorage.CreateChapterAsync(chapter);

            _logger.LogInformation($"创建章节成功，项目ID: {novelProjectId}, 章节: {chapterNumber}");
            return chapter;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"创建章节失败，项目ID: {novelProjectId}, 章节: {chapterNumber}");
            throw;
        }
    }

    public async Task<ChapterCreationResult> AutoGenerateChapterAsync(int chapterId, IProgress<ChapterCreationProgress>? progressCallback = null)
    {
        var startTime = DateTime.Now;
        var result = new ChapterCreationResult();

        try
        {
            var chapter = await _dataStorage.GetChapterAsync(chapterId);
            var novelProject = chapter != null ? await _dataStorage.GetNovelProjectAsync(chapter.NovelProjectId) : null;

            if (chapter == null)
            {
                result.ErrorMessage = "章节不存在";
                return result;
            }

            var targetWordCount = novelProject?.TargetWordsPerChapter ?? 6500;

            // 报告进度：开始
            progressCallback?.Report(new ChapterCreationProgress
            {
                ChapterId = chapterId,
                CurrentWordCount = 0,
                TargetWordCount = targetWordCount,
                ProgressPercentage = 0,
                CurrentPhase = "准备阶段",
                Status = "正在分析上下文..."
            });

            // 获取章节大纲
            var outline = !string.IsNullOrEmpty(chapter.Summary) ? chapter.Summary :
                await GenerateChapterOutlineAsync(chapter.NovelProjectId, new VolumeOutline(), chapter.ChapterNumber);

            // 报告进度：生成内容
            progressCallback?.Report(new ChapterCreationProgress
            {
                ChapterId = chapterId,
                CurrentWordCount = 0,
                TargetWordCount = targetWordCount,
                ProgressPercentage = 25,
                CurrentPhase = "内容生成",
                Status = "正在生成章节内容..."
            });

            // 生成章节内容
            var content = await GenerateChapterContentAsync(chapter.NovelProjectId, outline, chapter.ChapterNumber, targetWordCount);

            // 报告进度：一致性检查
            progressCallback?.Report(new ChapterCreationProgress
            {
                ChapterId = chapterId,
                CurrentWordCount = content.Length,
                TargetWordCount = targetWordCount,
                ProgressPercentage = 75,
                CurrentPhase = "质量检查",
                Status = "正在进行一致性检查..."
            });

            // 一致性检查
            var consistencyResult = await CheckConsistencyAsync(chapter.NovelProjectId, chapter.ChapterNumber, content);
            if (!consistencyResult.IsConsistent)
            {
                result.Warnings.AddRange(consistencyResult.Issues);
                result.Suggestions.AddRange(consistencyResult.Suggestions);
            }

            // 更新章节
            chapter.Content = content;
            chapter.WordCount = content.Length;
            chapter.Status = "Completed";
            chapter.UpdatedAt = DateTime.Now;
            await _dataStorage.UpdateChapterAsync(chapter);

            // 更新角色属性
            await UpdateCharacterAttributesAsync(chapter.NovelProjectId, content, chapter.ChapterNumber);

            // 报告进度：完成
            progressCallback?.Report(new ChapterCreationProgress
            {
                ChapterId = chapterId,
                CurrentWordCount = content.Length,
                TargetWordCount = targetWordCount,
                ProgressPercentage = 100,
                CurrentPhase = "完成",
                Status = "章节创作完成"
            });

            result.IsSuccess = true;
            result.Content = content;
            result.WordCount = content.Length;
            result.IsCompleted = true;
            result.CreationTime = DateTime.Now - startTime;

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"自动生成章节失败，章节ID: {chapterId}");
            result.ErrorMessage = ex.Message;
            result.CreationTime = DateTime.Now - startTime;
            return result;
        }
    }

    public async Task<ChapterCreationResult> ContinueChapterCreationAsync(int chapterId, IProgress<ChapterCreationProgress>? progressCallback = null)
    {
        // 简化实现：调用自动生成
        return await AutoGenerateChapterAsync(chapterId, progressCallback);
    }

    public async Task<ConsistencyCheckResult> CheckChapterConsistencyAsync(int chapterId, string currentContent)
    {
        try
        {
            var chapter = await _dataStorage.GetChapterAsync(chapterId);

            if (chapter == null)
            {
                return new ConsistencyCheckResult
                {
                    IsConsistent = false,
                    Issues = new List<string> { "章节不存在" }
                };
            }

            return await CheckConsistencyAsync(chapter.NovelProjectId, chapter.ChapterNumber, currentContent);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"检查章节一致性失败，章节ID: {chapterId}");
            return new ConsistencyCheckResult
            {
                IsConsistent = false,
                Issues = new List<string> { $"检查失败: {ex.Message}" }
            };
        }
    }

    public async Task<string> GenerateChapterEndingAsync(int chapterId, string currentContent)
    {
        try
        {
            var chapter = await _dataStorage.GetChapterAsync(chapterId);

            if (chapter == null)
            {
                throw new ArgumentException("章节不存在");
            }

            var prompt = $@"
请为以下章节内容生成一个合适的结尾：

当前章节内容：
{currentContent}

要求：
1. 结尾要与前文自然衔接
2. 为下一章留下适当的悬念或过渡
3. 符合章节的整体节奏
4. 字数控制在200-500字

请生成章节结尾：
";

            var ending = await _aiService.GenerateTextAsync(prompt, 1000, 0.8f);
            _logger.LogInformation($"生成章节结尾完成，章节ID: {chapterId}");
            return ending;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"生成章节结尾失败，章节ID: {chapterId}");
            throw;
        }
    }

    public async Task<List<Character>> UpdateCharacterAttributesAsync(int novelProjectId, string chapterContent, int chapterNumber)
    {
        try
        {
            var characters = await _dataStorage.GetCharactersAsync(novelProjectId);

            await UpdateCharacterAttributesAsync(novelProjectId, chapterContent, chapterNumber);

            // 重新获取更新后的角色
            return await _dataStorage.GetCharactersAsync(novelProjectId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"更新角色属性失败，项目ID: {novelProjectId}");
            return new List<Character>();
        }
    }

    public async Task<string> GetRelevantHistoryContextAsync(int novelProjectId, int currentChapter, ContextType contextType)
    {
        try
        {
            var query = contextType switch
            {
                ContextType.Character => "角色 人物 性格 属性",
                ContextType.Plot => "情节 剧情 发展 事件",
                ContextType.Setting => "设定 世界观 背景 环境",
                ContextType.Previous => $"第{currentChapter - 1}章",
                _ => "相关内容"
            };

            var relatedContent = await GetRelatedHistoryContentAsync(novelProjectId, query);
            return string.Join("\n\n", relatedContent);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"获取相关历史上下文失败，项目ID: {novelProjectId}");
            return "";
        }
    }

    public async Task<ChapterProgress> GetChapterProgressAsync(int chapterId)
    {
        try
        {
            var chapter = await _dataStorage.GetChapterAsync(chapterId);
            if (chapter == null)
            {
                throw new ArgumentException("章节不存在");
            }

            var targetWordCount = 6500; // 默认目标字数
            var completionPercentage = targetWordCount > 0 ?
                Math.Min(100, (float)chapter.WordCount / targetWordCount * 100) : 0;

            return new ChapterProgress
            {
                ChapterId = chapterId,
                WordCount = chapter.WordCount,
                TargetWordCount = targetWordCount,
                CompletionPercentage = completionPercentage,
                Status = chapter.Status,
                LastModified = chapter.UpdatedAt,
                ConsistencyChecks = new List<ConsistencyCheckResult>(),
                IsAutoGenerating = false
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"获取章节进度失败，章节ID: {chapterId}");
            throw;
        }
    }

    public async Task<bool> PauseChapterCreationAsync(int chapterId)
    {
        try
        {
            var chapter = await _dataStorage.GetChapterAsync(chapterId);
            if (chapter == null) return false;

            chapter.Status = "Paused";
            chapter.UpdatedAt = DateTime.Now;
            await _dataStorage.UpdateChapterAsync(chapter);

            _logger.LogInformation($"暂停章节创作，章节ID: {chapterId}");
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"暂停章节创作失败，章节ID: {chapterId}");
            return false;
        }
    }

    public async Task<bool> CompleteChapterAsync(int chapterId)
    {
        try
        {
            var chapter = await _dataStorage.GetChapterAsync(chapterId);
            if (chapter == null) return false;

            chapter.Status = "Completed";
            chapter.UpdatedAt = DateTime.Now;
            await _dataStorage.UpdateChapterAsync(chapter);

            _logger.LogInformation($"完成章节创作，章节ID: {chapterId}");
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"完成章节创作失败，章节ID: {chapterId}");
            return false;
        }
    }

    public async Task<NovelCreationStatistics> GetCreationStatisticsAsync(int novelProjectId)
    {
        try
        {
            var chapters = await _dataStorage.GetChaptersAsync(novelProjectId);

            var characters = await _dataStorage.GetCharactersAsync(novelProjectId);

            var totalChapters = chapters.Count;
            var completedChapters = chapters.Count(c => c.Status == "Completed");
            var inProgressChapters = chapters.Count(c => c.Status == "InProgress" || c.Status == "Draft");
            var totalWordCount = chapters.Sum(c => c.WordCount);
            var averageWordsPerChapter = totalChapters > 0 ? totalWordCount / totalChapters : 0;
            var completionPercentage = totalChapters > 0 ? (float)completedChapters / totalChapters * 100 : 0;

            return new NovelCreationStatistics
            {
                TotalChapters = totalChapters,
                CompletedChapters = completedChapters,
                InProgressChapters = inProgressChapters,
                PlannedChapters = Math.Max(0, 1000 - totalChapters), // 假设目标1000章
                TotalWordCount = totalWordCount,
                AverageWordsPerChapter = averageWordsPerChapter,
                CompletionPercentage = completionPercentage,
                TotalCreationTime = TimeSpan.Zero, // 需要额外跟踪
                LastCreationDate = chapters.Any() ? chapters.Max(c => c.UpdatedAt) : DateTime.MinValue,
                CharacterCount = characters.Count,
                CharacterAppearances = new Dictionary<string, int>() // 需要额外分析
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"获取创作统计失败，项目ID: {novelProjectId}");
            throw;
        }
    }

    /// <summary>
    /// 根据世界设定生成全书大纲
    /// </summary>
    public async Task<string> GenerateOverallOutlineWithWorldSettingAsync(int novelProjectId, string creativeDirection, WorldSetting worldSetting, int volumeCount = 10)
    {
        try
        {
            var novelProject = await _dataStorage.GetNovelProjectAsync(novelProjectId);

            if (novelProject == null)
            {
                _logger.LogError($"小说项目不存在: {novelProjectId}");
                throw new ArgumentException($"小说项目不存在: {novelProjectId}。请确保项目已正确创建。");
            }

            var worldSettingJson = JsonConvert.SerializeObject(worldSetting, Formatting.Indented);

            var prompt = $@"
请基于以下世界设定为小说项目生成一个详细的全书大纲：

小说标题：{novelProject.Title}
创作方向：{creativeDirection}
目标章节数：{novelProject.TargetChapterCount}
每章字数：{novelProject.TargetWordsPerChapter}
分卷数量：{volumeCount}卷

世界设定：
{worldSettingJson}

请生成一个包含以下内容的全书大纲：
1. 故事背景和世界观设定（基于提供的世界设定）
2. 主要角色介绍和关系
3. 核心冲突和主线情节
4. 分卷结构建议（请严格按照{volumeCount}卷进行规划）
5. 整体故事发展脉络
6. 预期的高潮和结局

要求：
- 严格遵循提供的世界设定
- 确保各卷之间的逻辑连贯性
- 为每卷设定明确的主题和目标
- 考虑角色成长和情节发展的节奏
- 大纲应该为后续的分卷大纲和章节创作提供充分指导

请生成详细的全书大纲：
";

            var outline = await _aiService.GenerateTextAsync(prompt, 3000, 0.8f);

            // 保存大纲到数据存储
            novelProject.OverallOutline = outline;
            novelProject.UpdatedAt = DateTime.Now;
            await _dataStorage.UpdateNovelProjectAsync(novelProject);

            _logger.LogInformation($"基于世界设定生成全书大纲完成，项目ID: {novelProjectId}");
            return outline;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"基于世界设定生成全书大纲失败，项目ID: {novelProjectId}");
            throw;
        }
    }

    /// <summary>
    /// 根据时间线生成分卷大纲
    /// </summary>
    public async Task<VolumeOutline> GenerateVolumeOutlineWithTimelineAsync(int novelProjectId, string overallOutline, int volumeNumber, int totalVolumes, int startChapter, int endChapter, string previousVolumeTimeline)
    {
        try
        {
            var novelProject = await _dataStorage.GetNovelProjectAsync(novelProjectId);

            if (novelProject == null)
            {
                _logger.LogError($"小说项目不存在: {novelProjectId}");
                throw new ArgumentException($"小说项目不存在: {novelProjectId}。请确保项目已正确创建。");
            }

            var prompt = $@"
基于以下信息，请为第{volumeNumber}卷生成详细的分卷大纲：

全书大纲：
{overallOutline}

第{volumeNumber}卷信息：
- 卷数：{volumeNumber}/{totalVolumes}
- 章节范围：第{startChapter}章 - 第{endChapter}章
- 预计章节数：{endChapter - startChapter + 1}

前一卷时间线参考：
{(string.IsNullOrEmpty(previousVolumeTimeline) ? "无（这是第一卷）" : previousVolumeTimeline)}

请生成包含以下内容的分卷大纲：
1. 本卷的核心主题和目标
2. 主要情节发展（要与全书大纲保持一致）
3. 角色成长和变化
4. 重要事件和转折点
5. 与前后卷的衔接（特别是与前一卷时间线的连接）
6. 本卷的高潮和结尾
7. 为后续章节创作提供的具体指导

要求：
- 严格遵循全书大纲的设定
- 如果有前一卷时间线，确保情节的连贯性
- 为每个章节范围提供明确的创作方向
- 考虑本卷在整个故事中的作用和地位

请生成详细的分卷大纲：
";

            var volumeOutlineText = await _aiService.GenerateTextAsync(prompt, 2500, 0.8f);

            var volumeOutline = new VolumeOutline
            {
                VolumeNumber = volumeNumber,
                Title = $"第{volumeNumber}卷",
                Description = volumeOutlineText,
                StartChapter = startChapter,
                EndChapter = endChapter,
                MainPlot = $"第{volumeNumber}卷主要情节",
                KeyEvents = new List<string>(),
                CharacterDevelopments = new List<string>()
            };

            _logger.LogInformation($"基于时间线生成第{volumeNumber}卷大纲完成，项目ID: {novelProjectId}");
            return volumeOutline;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"基于时间线生成第{volumeNumber}卷大纲失败，项目ID: {novelProjectId}");
            throw;
        }
    }

    /// <summary>
    /// 根据时间线生成章节细纲
    /// </summary>
    public async Task<string> GenerateChapterOutlineWithTimelineAsync(int novelProjectId, VolumeOutline volumeOutline, int chapterNumber, string previousChapterTimeline)
    {
        try
        {
            var novelProject = await _dataStorage.GetNovelProjectAsync(novelProjectId);

            if (novelProject == null)
            {
                _logger.LogError($"小说项目不存在: {novelProjectId}");
                throw new ArgumentException($"小说项目不存在: {novelProjectId}。请确保项目已正确创建。");
            }

            var prompt = $@"
基于以下信息，请为第{chapterNumber}章生成详细的章节细纲：

分卷大纲：
{volumeOutline.Description}

章节信息：
- 章节号：第{chapterNumber}章
- 所属卷：第{volumeOutline.VolumeNumber}卷
- 在本卷中的位置：第{chapterNumber - volumeOutline.StartChapter + 1}章（共{volumeOutline.EndChapter - volumeOutline.StartChapter + 1}章）

前一章时间线参考：
{(string.IsNullOrEmpty(previousChapterTimeline) ? "无（这是本卷第一章）" : previousChapterTimeline)}

请按照以下结构生成章节细纲：

## 第{chapterNumber}章细纲

### 场景设定
- 时间：
- 地点：
- 环境描述：

### 主要人物
- 出场角色：
- 角色状态：
- 角色关系：

### 主线情节
- 开篇情况：
- 主要事件：
- 冲突点：
- 转折点：

### 爽点/悬念
- 爽点设计：
- 悬念设置：
- 读者期待：

### 章节结果
- 情节结果：
- 角色变化：
- 为下章铺垫：

要求：
- 严格遵循分卷大纲的设定
- 如果有前一章时间线，确保情节的连贯性
- 细纲要具体可操作，为正文创作提供明确指导
- 考虑章节在整卷中的作用和节奏

请生成详细的章节细纲：
";

            var chapterOutline = await _aiService.GenerateTextAsync(prompt, 1500, 0.8f);

            _logger.LogInformation($"基于时间线生成第{chapterNumber}章细纲完成，项目ID: {novelProjectId}");
            return chapterOutline;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"基于时间线生成第{chapterNumber}章细纲失败，项目ID: {novelProjectId}");
            throw;
        }
    }
}


